package com.roden.study.redis.util;

import com.roden.study.redis.jedis.JedisUtil;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @Author luodeng
 * @create 2021/4/2 17:14
 */
public class UniqueSequenceNo {
    public static final String DISTRIBUTED_SEQUENCE="distributed:sequence:";
    public static final String pattern="yyyyMMdd";
    static DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern(pattern);

    public static String getUniqueNo(){
       return getUniqueNo("");
    }
    
    public static String getUniqueNo(String prefix){
        String date=dateTimeFormatter.format(LocalDate.now());
        return prefix+date+String.format("%08d",getSequence(prefix,date));
    }

    private static Long getSequence(String prefix,String date){
        String key=DISTRIBUTED_SEQUENCE+prefix+date;
        Long sequence= JedisUtil.getJedis().incr(key);
        if(sequence==1){
            JedisUtil.getJedis().expire(key,60*60*24*2);
        }
        return sequence;
    }

    public static void main(String[] args) {
        for(int i=0;i<10;i++){
            new Thread(()->{
                System.out.println(getUniqueNo("DF"));
                System.out.println(getUniqueNo());
            }).start();
        }
    }
}
